package moe.oil.db.service;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import moe.oil.db.entity.Comments;
import moe.oil.db.repo.CommentsRepo;
import moe.oil.db.repo.SchoolRepo;
import moe.oil.db.repo.UserRepo;
import moe.oil.dto.school.CommentsDTO;
import moe.oil.exception.comments.CommentsIdNullException;
import moe.oil.exception.school.SchoolIdNotFoundException;
import moe.oil.exception.user.UserIdNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@Setter(onMethod_ = @Autowired)
@Log4j2
public class CommentsService implements BaseService<CommentsDTO, CommentsRepo> {

    //todo 使用 openfegin 发送 请求获取数据
    private CommentsRepo commentsRepo;
    private SchoolRepo schoolRepo;
    private UserRepo userRepo;

    // 根据Id查询评论
    public Optional<CommentsDTO> selectCommentsId(Long id) {
        return Optional.of(commentsRepo.findByCommentId(id).orElseThrow(() -> new CommentsIdNullException(id)).convert());
    }

    // 查询全部评论
    public List<CommentsDTO> selectCommentsAll(PageRequest pageRequest) {
        return commentsRepo.findAll(pageRequest)
                .stream().map(Comments::convert)
                .collect(java.util.stream.Collectors.toList());
    }

    // 添加评论
    public Optional<CommentsDTO> saveComments(CommentsDTO commentsDto) {
        var school = schoolRepo.findBySchoolId(commentsDto.getSchoolDTO().getSchoolId()).orElseThrow(() -> new SchoolIdNotFoundException(commentsDto.getSchoolDTO().getSchoolId()));
        var user = userRepo.findByUserId(commentsDto.getUserDTO().getUserId()).orElseThrow(() -> new UserIdNotFoundException(commentsDto.getUserDTO().getUserId()));
        var comments = new Comments(commentsDto)
                .setSchool(school)
                .setUsers(user);
        log.info(comments);
        return Optional.of(commentsRepo.save(comments).convert());
    }

    // 根据ID删除评论
    public int deleteCommentsId(Long id) {
        var delete = commentsRepo.deleteByCommentId(id);
        if (delete != 0) {
            return delete;
        } else {
            throw new CommentsIdNullException(id);
        }
    }

    // 修改
    public Optional<CommentsDTO> updateComments(Comments comments) {
        if (comments.getCommentId() != null && comments.getCommentId() != 0) {
            return Optional.of(commentsRepo.save(comments).convert());
        } else {
            throw new CommentsIdNullException(comments.getCommentId());
        }
    }
}
